package com.iampzh.springvue.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.iampzh.springvue.comm.MyResult;
import com.iampzh.springvue.entity.User;
import com.iampzh.springvue.mapper.FileMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
@CrossOrigin
@RestController
@RequestMapping("/file")
public class FileController {
    @Value("${files.upload.path}")
    private String filePath;
    @Autowired
    private FileMapper fileMapper;

    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        long size = file.getSize();
        String type = FileUtil.extName(originalFilename);
        File file1 = new File(filePath);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        String uuid = IdUtil.fastSimpleUUID();
       
      String  filePath1 = file1 + "/" + uuid + StrUtil.DOT + type;

        File fileupload = new File(filePath1);
        file.transferTo(fileupload);
        com.iampzh.springvue.entity.File saveFile = new com.iampzh.springvue.entity.File();
        saveFile.setType(type);
        saveFile.setSize(size/1024);
        saveFile.setName(originalFilename);
        saveFile.setUrl(uuid);
        saveFile.setUuid(uuid);
        fileMapper.insert(saveFile);
        return filePath;
    }
    @GetMapping("/page")
    public Page<com.iampzh.springvue.entity.File> findUsersPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize,
                                                                @RequestParam(defaultValue = "") String name){
        Page<com.iampzh.springvue.entity.File> page=new Page<>(pageNum,pageSize);
        QueryWrapper<com.iampzh.springvue.entity.File> queryWrapper=new QueryWrapper<>();
        if(!"".equals(name)){
            queryWrapper.like("name",name);
        }
queryWrapper.eq("is_del",false);
        queryWrapper.orderByDesc("id");
        return fileMapper.selectPage(page,queryWrapper);
    }
    @PostMapping("deleteIds")
    public Integer deleteIds(@RequestBody List<Integer> ids){
QueryWrapper<com.iampzh.springvue.entity.File> fileQueryWrapper=new QueryWrapper<>();
fileQueryWrapper.in("id",ids);
        List<com.iampzh.springvue.entity.File> files = fileMapper.selectList(fileQueryWrapper);
        for (com.iampzh.springvue.entity.File file:files
             ) {
            file.setIsDel(true);
fileMapper.updateById(file);
        }

        return fileMapper.deleteBatchIds(ids);
    }
    @PostMapping("/updata")
    public MyResult updataFile(@RequestBody com.iampzh.springvue.entity.File file){
        int i = fileMapper.updateById(file);
        return MyResult.success();
    }
    /**
     * 文件下载接口   http://localhost:9090/file/{fileUUID}
     * @param fileUUID
     * @param response
     * @throws IOException
     */
    @GetMapping("/{fileUUID}")
    public void download(@PathVariable String fileUUID, HttpServletResponse response) throws IOException {
        QueryWrapper<com.iampzh.springvue.entity.File> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("uuid",fileUUID);
        com.iampzh.springvue.entity.File file1 = fileMapper.selectOne(queryWrapper);
        String name = file1.getName();
        try {
            // path是指想要下载的文件的路径
            File file = new File(filePath+fileUUID+"."+file1.getType());

            // 获取文件名
            String filename = file.getName();


            // 将文件写入输入流
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();

            // 清空response
       response.reset();
            // 设置response的Header
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Access-Control-Allow-Origin", "*");
            //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
            //attachment表示以附件方式下载   inline表示在线打开   "Content-Disposition: inline; filename=文件名.mp3"
            // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
           // response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(name+"."+file1.getType(), "UTF-8"));
           response.addHeader("Content-Disposition",  "attachment;filename=" + URLEncoder.encode(name+"."+file1.getType(), "UTF-8"));

            // 告知浏览器文件的大小
            response.addHeader("Content-Length", "" + file.length());
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            outputStream.write(buffer);
            outputStream.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
